package com.dz.scrm.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.provider.Settings
import com.dz.scrm.constant.CACHE_CHECK_UPDATE
import com.dz.scrm.constant.CACHE_LOGIN_STATE
import com.dz.scrm.constant.INTENT_REQUEST_PERMISSION
import com.dz.scrm.mvp.model.entity.CheckVersionBean
import com.dz.scrm.mvp.model.entity.CompanyInfoBean
import com.dz.scrm.mvp.presenter.DZPresent
import com.dz.scrm.mvp.ui.DZActivity
import com.dz.scrm.mvp.ui.LoginActivity
import com.dz.scrm.utils.SharedPreferencesUtil.CALL_PHONE_NUM
import com.dz.scrm.utils.SharedPreferencesUtil.COMPANY_INFO
import com.dz.scrm.view.UpdateVersionDialog
import com.lxj.xpopup.XPopup
import com.miui.enterprise.sdk.PhoneManager
import me.jessyan.art.integration.AppManager
import java.lang.Integer.parseInt
import java.text.SimpleDateFormat
import java.util.*

/**
 * 作者：fanda
 * 日期：2021/4/23 15:44
 * 描述：
 */

// 启动 Activity 的快捷方法

inline fun <reified T> launchActivity(context: Context) {
    context.startActivity(Intent(context, T::class.java))
}

inline fun <reified T> launchActivity(context: Context, block: Intent.() -> Unit) {
    val intent = Intent(context, T::class.java)
    intent.block()
    context.startActivity(intent)
}

/**
 * 作者：fanda
 * 时间：2020/7/28 19:07
 * 描述：跳转到设置界面
 */
fun Activity.intentToSettingActivity() {
    val intent = Intent().apply {
        action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        data = Uri.fromParts("package", packageName, null)
    }
    startActivityForResult(intent, INTENT_REQUEST_PERMISSION)
}

val DUAL_SIM_TYPES = arrayOf("subscription",
        "Subscription",
        "com.android.phone.extra.slot",
        "phone",
        "com.android.phone.DialingMode",
        "simId",
        "simnum",
        "phone_type",
        "simSlot")

/**
 *
 * 拨打电话（拨号权限自行处理）
 *
 * @param phoneNum ：目标手机号
 *
 * @param simIndex ：sim卡的位置 0代表sim卡1，1代表sim卡2
 */
fun Activity.callPhone(phoneNum: String, simIndex: Int) {
    PhoneManager.getInstance().setPhoneCallAutoRecord(true)
    startActivity(Intent(Intent.ACTION_CALL).apply {
        flags = Intent.FLAG_ACTIVITY_NEW_TASK
        data = Uri.parse(phoneNum)
        //记录当前拨出去的电话
        SharedPreferencesUtil.saveInfo(CALL_PHONE_NUM, phoneNum)
        for (dualSimType in DUAL_SIM_TYPES) {
            putExtra(dualSimType, simIndex)
        }
    })
}

/***
 * 单卡拨打电话
 */
fun Activity.callPhone(phoneNum: String) {
    //开启电话自动录音
    PhoneManager.getInstance().setPhoneCallAutoRecord(true)
    //记录当前拨出去的电话
    SharedPreferencesUtil.saveInfo(CALL_PHONE_NUM, phoneNum)
    startActivity(Intent(Intent.ACTION_CALL).apply {
        data = Uri.parse("tel:$phoneNum")
    })
}

fun getEncryptPhoneNum(phoneNum: String): String {
    if (phoneNum.isNotEmpty() && phoneNum in "0".."9" && phoneNum.length == 11) {
        // 不包括 endIndex
        val encrypt = phoneNum.replaceRange(3, 7, "****")
        val middleNum = " " + encrypt.substring(3, 7) + " "
        return phoneNum.replaceRange(3, 7, middleNum)
    }
    return phoneNum
}

fun getFormatPhoneNum(phoneNum: String): String {
    if (phoneNum.isNotEmpty() && phoneNum in "0".."9" && phoneNum.length == 11) {
        val middleNum = " " + phoneNum.substring(3, 7) + " "
        return phoneNum.replaceRange(3, 7, middleNum)
    }
    return phoneNum
}

fun getCheckVersionBean(): CheckVersionBean? {
    val info = SharedPreferencesUtil.getInfo(CACHE_CHECK_UPDATE)
    return if (!info.isNullOrEmpty()) {
        JsonHelper.parserJson2Object(info, CheckVersionBean::class.java)
    } else {
        null
    }
}

fun getCompanyInfoBean(): CompanyInfoBean? {
    val info = SharedPreferencesUtil.getInfo(COMPANY_INFO)
    return if (!info.isNullOrEmpty()) {
        JsonHelper.parserJson2Object(info, CompanyInfoBean::class.java)
    } else {
        null
    }
}

/*通用的获取 json 实体类的方法*/
inline fun <reified T> getInfoBean(key: String): T? {
    val info = SharedPreferencesUtil.getInfo(key)
    return if (!info.isNullOrEmpty()) {
        JsonHelper.parserJson2Object(info, T::class.java)
    } else {
        null
    }
}

fun getUserId() = getInfoBean<CompanyInfoBean>(COMPANY_INFO)?.user_id ?: ""
fun isHiddenPhoneNum() = getInfoBean<CompanyInfoBean>(COMPANY_INFO)?.is_hidden ?: false
fun getTenantId() = getInfoBean<CompanyInfoBean>(COMPANY_INFO)?.tenant_id ?: ""
fun getToken() = getInfoBean<CompanyInfoBean>(COMPANY_INFO)?.access_token ?: ""

// 是否已经登录
fun isAlreadyLogin() = SharedPreferencesUtil.getStatus(CACHE_LOGIN_STATE)

fun DZActivity<DZPresent>.showCheckVersionDialog(checkVersionBean: CheckVersionBean) {
    XPopup.Builder(this).dismissOnBackPressed(!checkVersionBean.upgrade!!)
            .isDestroyOnDismiss(true)
            .dismissOnTouchOutside(!checkVersionBean.upgrade).asCustom(UpdateVersionDialog(this, checkVersionBean))
            .show()
}

// 清除登录相关缓存
fun clearCacheInfo() {
    SharedPreferencesUtil.remove(CACHE_LOGIN_STATE)
}

fun Activity.switchAccount() {
    clearCacheInfo()
    launchActivity<LoginActivity>(this)
    AppManager.getAppManager().killAll()
}

// 网络是否连接
fun Activity.isNetworkAvailable(): Boolean {
    val connectivity = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val info = connectivity.activeNetworkInfo
    if (info != null && info.isConnected) {
        // 当前网络是连接的
        // 当前所连接的网络可用
        return info.state == NetworkInfo.State.CONNECTED
    }
    return false
}

fun getPhoneDate(dateLong: Long): String {
    //拨打时间
    var date = Date(System.currentTimeMillis())
    val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd")
    val date_today = simpleDateFormat.format(date)
    var sdf = SimpleDateFormat("yyyy-MM-dd")
    val callDate = Date(dateLong)
    var callDateStr: String = sdf.format(callDate)
    if (callDateStr == date_today) { //判断是否为今天
        sdf = SimpleDateFormat("HH:mm")
        callDateStr = sdf.format(callDate)
    } else if (date_today.contains(callDateStr.substring(0, 7))) { //判断是否为当月
        sdf = SimpleDateFormat("dd")
        val callDay: Int = Integer.valueOf(sdf.format(callDate))
        val day: Int = Integer.valueOf(sdf.format(date))
        if (day - callDay == 1) {
            callDateStr = "昨天"
        } else {
            sdf = SimpleDateFormat("MM-dd")
            callDateStr = sdf.format(callDate)
        }
    } else if (date_today.contains(callDateStr.substring(0, 4))) { //判断是否为当年
        sdf = SimpleDateFormat("MM-dd")
        callDateStr = sdf.format(callDate)
    }
    return callDateStr
}

fun calculateDiffTime(startStamp: Long, endStamp: Long): Long {
    return endStamp / 1000 - startStamp / 1000
}
